﻿using BusinessLayer.VDataEntities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CustomerServiceCenter.Helper {
    public class AuthenticationAttribute : AuthorizeAttribute {

        public override void OnAuthorization(AuthorizationContext filterContext) {
            //TO DO: whether System.Web.HttpContext.Current.Session["CurrentUser"] is valid
            //base.OnAuthorization(filterContext);
            if (HttpContext.Current.Session == null) {
                //
                ProcessNotLogin(filterContext);
            }
            else  {
                if (HttpContext.Current.Session["Admininfo"] as VSuperDataEntity == null) {
                    VSuperDataEntity CurrentUser = new VSuperDataEntity();
#if(DEBUG)
                    {
                        //以Debug模式运行时会执行
                        if (string.IsNullOrEmpty(CurrentUser.Name))
                        {
                            CurrentUser = new VSuperDataEntity { ID = 1, Name = "TestAdmin" };
                            System.Web.HttpContext.Current.Session["AdminInfo"] = CurrentUser;
                        }
                        else
                        {
                            CurrentUser = System.Web.HttpContext.Current.Session["AdminInfo"] as VSuperDataEntity;
                        }
                    }
#endif
                }
            }
        }

        void ProcessNotLogin(AuthorizationContext filterContext, bool bfillresult = true) {
            if (filterContext.RequestContext.HttpContext.Request.IsAjaxRequest()) {
                HttpContext.Current.Response.StatusCode = 200;
                if (filterContext.RequestContext.HttpContext.Request.RequestType == "POST")
                    filterContext.Result = new RedirectResult("/api/Common/Timeout");
                else
                    filterContext.Result = new RedirectResult("/api/Common/Timeout");
            }
            else
                filterContext.Result = new RedirectResult("/WeChat/Login");
        }





    }
}